package com.crystal.jcms.shpz;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.crystal.constant.Constant;
import com.crystal.jcms.ui.CustomTitleActivity;
import com.crystal.jcms.utils.RequestUtils;
import com.crystal.jcms.utils.RequestUtils.CallBack;
import com.crystal.jcms.utils.ShowMsgUtils;
import com.crystal.jcms.utils.SpUtils;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ActivityCard extends CustomTitleActivity {
	private Context mContext;
	String strId, strNbzlh, strItemName, strTestNo, flag, dbType = "";
	String strUrl, strCurrentUrl;
	WebView mWebView;

	@SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" })
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.activity_card);
		initWidget();
		initActionBar();

		new Thread(new Runnable() {
			public void run() {
				Message message = new Message();

				int iCode = getRespStatus(getUrl());
				if (iCode == 404) {
					message.what = 404;
				} else {
					message.what = 200;
				}
				handler.sendMessage(message);
			}
		}).start();
	}

	private void initWidget() {
		strId = getIntent().getStringExtra("Id");
		strNbzlh = getIntent().getStringExtra("Nbzlh");
		flag = getIntent().getStringExtra("Flag");
		strTestNo = getIntent().getStringExtra("TestNo");
		strItemName = getIntent().getStringExtra("ItemName");
		dbType = getIntent().getStringExtra("dbType");

		mWebView = (WebView) findViewById(R.id.webview);
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		mWebView.setWebViewClient(mWebViewClient);
		mWebView.addJavascriptInterface(this, "elva");
		mForwardButton.setOnClickListener(new btnReportCheckOnClick());
	}

	private void initActionBar() {
		setTitle(strItemName + flag);
		showBackwardView(R.string.text_back, true);
		if (flag.equals("报告批准")) {
			showForwardView(R.string.pizhun, true);
		} else {
			showForwardView(R.string.shenhe, true);
		}
		// ActionBar actionBar = getActionBar();
		// actionBar.setTitle(strItemName + flag);
		// actionBar.setDisplayShowHomeEnabled(false);
		// actionBar.setDisplayHomeAsUpEnabled(false);
	}

	// 获取要加载的检测项目卡片地址
	private String getUrl() {
		String strConn = "";
		if (dbType.equals("sz")) {
			strConn = "connJc";
		} else {
			strConn = "connJcJy";
		}
		String serverUrl = SpUtils.get(mContext, "ServerUrl", "").toString();
		strUrl = serverUrl + "/rizhao/Page/Jcms/检测项目卡片/";
		strUrl += "frm检测项目卡片_" + strNbzlh + strItemName.replaceAll(" ", "") + ".htm";
		strUrl += "?ID=" + strId + "&JcCon=" + strConn + "&type=mobile";

		strCurrentUrl = strUrl;
		return strUrl;
	}

	WebViewClient mWebViewClient = new WebViewClient() {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			strCurrentUrl = url;
			if (url.startsWith("http://") && getRespStatus(url) == 404) {
				view.stopLoading();
				// 载入本地assets文件夹下面的错误提示页面404.html
				view.loadUrl("file:///android_asset/404.html");
			} else {
				view.loadUrl(url);
			}
			return true;
		}

		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			if (errorCode == HttpStatus.SC_NOT_FOUND) {
				mWebView.loadUrl("file:///android_assets/404.html");
			}
		}
	};

	private int getRespStatus(String url) {
		int status = -1;
		try {
			HttpHead head = new HttpHead(url);
			HttpClient client = new DefaultHttpClient();
			HttpResponse resp = client.execute(head);
			status = resp.getStatusLine().getStatusCode();
		} catch (Exception e) {
		}
		return status;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (strCurrentUrl.contains("frm检测项目卡片_")) {
			finish();
		} else {
			if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
				mWebView.goBack();
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}



	public List<Map<String, String>> getData() {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Map<String, String> param = new HashMap<String, String>();
		param.put("type", flag);
		param.put("nbzlh", strNbzlh);
		param.put("dbType", dbType);
		String result = RequestUtils.doPost(mContext, "list.xml", "GetItemList", param);
		Message message = new Message();
		message.what = Constant.SHOWTOAST;
		if (result.contains("500_")) {
			message.obj = result.substring(4);
			handler.sendMessage(message);
			return list;
		}
		try {
			JSONObject jsonResult = new JSONObject(result);
			if (!jsonResult.get("Result").equals("")) {
				JSONArray jsonArray = jsonResult.getJSONArray("Result");
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject object = jsonArray.getJSONObject(i);
					Map<String, String> map = new HashMap<String, String>();
					map.put("Id", object.getString("Id"));
					map.put("TestNo", object.getString("TestNo"));
					list.add(map);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return list;
	}
	
	private class btnReportCheckOnClick implements OnClickListener{

		@Override
		public void onClick(View v) {
			ReportCheck();
		}
		
	}

	// 报告审核批准
	public void ReportCheck() {
		new Thread(new Runnable() {
			public void run() {
				Map<String, String> params = new HashMap<String, String>();
				params.put("type", flag);
				params.put("nbzlh", strNbzlh);
				params.put("username", (String) SpUtils.get(mContext, "UserName", ""));
				params.put("testnos", "('" + strTestNo + "')");
				params.put("dbType", dbType);
				String result = RequestUtils.doPost(mContext, "shenpi.xml", "ExecuteCheck", params);
				try {
					Message message = new Message();
					message.what = Constant.SHOWTOAST;
					if (result.contains("500_")) {
						message.obj = result.substring(4);
						handler.sendMessage(message);
						return;
					}
					JSONObject jsonResult = new JSONObject(result);
					if (jsonResult.getBoolean("ReturnData")) {
						// 审核通过 如果该类别下还有待审核数据 自动展示下一份数据；如果是最后一份数据则返回待办列表页面
						List<Map<String, String>> list = getData();
						if (list.size() > 0) {
							strId = list.get(0).get("Id");
							strTestNo = list.get(0).get("TestNo");
							int iCode = getRespStatus(getUrl());
							if (iCode == 404) {
								message.what = 404;
							} else {
								message.what = 200;
							}
							handler.sendMessage(message);
						} else {
							Message msg = new Message();
							msg.what = Constant.SHOWPAGE;
							handler.sendMessage(msg);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	@SuppressLint("HandlerLeak")
	public Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Constant.SHOWPAGE:
				finish();
				break;
			case Constant.SHOWTOAST:
				ShowMsgUtils.ShowToast(mContext, (String) msg.obj);
				break;
			case Constant.SHOWMESSAGE:
				ShowMsgUtils.ShowMessage(mContext, (String) msg.obj);
				break;
			case 404:
				mWebView.loadUrl("file:///android_asset/404.html");
				break;
			case 200:
				mWebView.loadUrl(getUrl());
				break;
			}
		}
	};

}
